//
//  LoginViewController.m
//  CRSCMOA
//
//  Created by goldnut on 16/8/30.
//  Copyright © 2016年 王文晓. All rights reserved.
//

#import "LoginViewController.h"
#import "SwitchTheServer.h"

@interface LoginViewController ()<UITextFieldDelegate>


- (IBAction)SwitchTheServer:(UILongPressGestureRecognizer *)sender;

- (IBAction)mySwitch:(UISwitch *)sender;

@property (weak, nonatomic) IBOutlet UIImageView *topImageView;
@property (weak, nonatomic) IBOutlet UIView *myView;

@property (weak, nonatomic) IBOutlet UITextField *userNameField;

@property (weak, nonatomic) IBOutlet UITextField *passerWordField;

@property (nonatomic, strong) UIView *backView;
- (IBAction)loginBtnClick:(UIButton *)sender;
@property (nonatomic, strong) NSMutableArray *dataSourceMArr;   //存储Model的数组


@end

@implementation LoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.topImageView.userInteractionEnabled = YES;
    // Do any additional setup after loading the view from its nib.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBar.hidden = YES;
    
    if ([CurrentUserInfo sharedCurrentUserInfo].userName) {
        self.userNameField.text = [CurrentUserInfo sharedCurrentUserInfo].userName;
        self.passerWordField.text = [CurrentUserInfo sharedCurrentUserInfo].password;
        //        NSLog(@"------------%@",self.userNameField.text);
    }
}



#pragma mark  - 按钮回调 -

- (IBAction)loginBtnClick:(UIButton *)sender {
    
    //POST请求
    
    NSDictionary *mdic = [NSDictionary dictionaryWithObjectsAndKeys:self.userNameField.text,@"username",self.passerWordField.text,@"password",nil];
    [JNTDataRequestTools postFetchDataWithUrlString:Login_URL paramenters:mdic success:^(id data) {
        // 请求成功，解析数据
        NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
//        NSLog(@"%@",resultDic);
        NSDictionary *myResultDic = resultDic[@"record"];
        NSString *userIdStr = myResultDic[@"uid"];
        UID = userIdStr;
        NSArray *modulesArr = myResultDic[@"modules"];
        for (NSDictionary *dataDic in modulesArr) {
            homeModel *model = [[homeModel alloc] init];
            [model setValuesForKeysWithDictionary:dataDic];
            NAME = model.name;
//            NSLog(@"name===%@",model.name);
            [self.dataSourceMArr addObject:model];
        }
        
      
        int mrcode = [[resultDic objectForKey:@"success"] intValue];
        
        //   NSLog(@"===%@",resultDic);
        if (!mrcode){
            
            NSLog(@"密码错误");
            
        }else{
            
            [CurrentUserInfo sharedCurrentUserInfo].userName = self.userNameField.text;
            [CurrentUserInfo sharedCurrentUserInfo].password = self.passerWordField.text;
            
            //代码能走到这里说明已经登录成功
            NSDictionary * dicToken = [resultDic objectForKey:@"pageData"];
            NSString *token = [dicToken objectForKey:@"password"];//NSString *token
            float time = [[resultDic objectForKey:@"time"] floatValue];
            NSDate *now = [NSDate date];
            NSDate *endTime = [now dateByAddingTimeInterval:time];
            [APP_DEF setObject:token forKey:TOKEN_KEY];
            [APP_DEF setObject:endTime forKey:TIME_KEY];
            [APP_DEF setObject:self.userNameField.text  forKey:USER_NAME];//存储当前登录的用户名
            [APP_DEF synchronize];
            //  跳转到主界面
            JNTTabBarController *vc = [[JNTTabBarController alloc]init];
            vc.dataSourceMArr = self.dataSourceMArr; //请求成功之后将数据传到主页
            [self.navigationController pushViewController:vc animated:YES];
        }
        
    } fail:^{
        
        NSLog(@"话题列表请求失败");
    } view:self.view];
    
    
}

//长按手势切换服务器
- (IBAction)SwitchTheServer:(UILongPressGestureRecognizer *)sender {
    //    蒙版视图
    self.backView = [[UIView alloc]initWithFrame:kRect(0, 0, kScreenWidth, kScreenHeight)];
    self.backView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.3];
    self.backView.hidden = YES;//一开始隐藏蒙版，点击cell时出现，点击取消按钮又隐藏
    [self.view addSubview:self.backView];
    //获得xib的UIView--头视图下面的View
    UINib *nib = [UINib nibWithNibName:@"SwitchTheServer" bundle:nil];
    SwitchTheServer *myAlert = [[nib instantiateWithOwner:nil options:nil] firstObject];
    myAlert.frame = kRect(10, kScreenHeight/4, kScreenWidth-20, 230);
    myAlert.backgroundColor = [UIColor whiteColor];
    myAlert.center = self.view.center;
    myAlert.navc = self.navigationController;
    self.backView.hidden = NO;
    myAlert.view = self.backView;
    myAlert.textField.delegate = self;
    [self.backView addSubview:myAlert];
    
}

//记住密码
- (IBAction)mySwitch:(UISwitch *)sender {
//    NSLog(@"%lu",(unsigned long)sender.state);
    
    if (sender.state == NO) {
        
        
        if ([CurrentUserInfo sharedCurrentUserInfo].userName) {
            
            self.userNameField.text = [CurrentUserInfo sharedCurrentUserInfo].userName;
            self.passerWordField.text = [CurrentUserInfo sharedCurrentUserInfo].password;
            
        }
        [sender setSelected:YES];
    }else{
        [sender setSelected:NO];
    }
    
}

//退出该应用
- (void)rightBtnClick
{
    JNTHomeViewController *homeVC = [[JNTHomeViewController alloc]init];
    homeVC.dataSourceMArr = self.dataSourceMArr;
    [self.navigationController pushViewController:homeVC animated:YES];
}

#pragma mark - 设置导航条
- (void)setUpNavgationBar
{
    self.navigationController.navigationBar.translucent = NO;
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"上栏"] forBarMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor]}];
    self.navigationItem.rightBarButtonItem =  [UIBarButtonItem rightBarButtonItemTarget:self title:@"退出" action:@selector(rightBtnClick) forControlEvents:UIControlEventValueChanged];
}

#pragma mark  - textFieldDelegate -
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    if (textField == self.userNameField) {
        [self.passerWordField resignFirstResponder];
        
    }else if (textField == self.passerWordField)
    {
        [self.userNameField resignFirstResponder];
        
    }
    
}


- (NSMutableArray *)dataSourceMArr{
    
    if (!_dataSourceMArr) {
        
        _dataSourceMArr = [NSMutableArray array];
    }
    return _dataSourceMArr;
}

@end
